﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApi.Core.IRepository;
using WebApi.Core.Model;
using WebApi.Core.Repository.Base;
using WebApi.Core.Repository.SqlSugar;

namespace WebApi.Core.Repository
{
    public class RefreshTokenRepository : BaseRepository<RefreshToken>,IRefreshTokenRepository
    {
        public RefreshTokenRepository(ILogger<RefreshTokenRepository> logger) :base(logger)
        {

        }

        public async Task<int> CountActiveTokensAsync(string userId)
        {
            return await _db.Queryable<RefreshToken>()
                .Where(rt =>rt.UserId == userId && !rt.IsUsed && !rt.IsRevoked && rt.ExpiryTime > DateTime.Now)
                .CountAsync();
        }

        public async Task RevokeAllTokensAsync(string userId)
        {
            await _db.Updateable<RefreshToken>()
                .SetColumns(rt => rt.IsRevoked == true)
                .Where(rt => rt.UserId == userId)
                .ExecuteCommandAsync();
        }
    }
}
